package com.mzj.saas.jobs.EnterpriseData.service;

import com.mzj.saas.jobs.EnterpriseData.entity.DayUseUserNum;
import com.mzj.saas.jobs.EnterpriseData.entity.DepartmentHierarchy;
import com.mzj.saas.jobs.EnterpriseData.entity.UserStatistics;
import com.mzj.saas.jobs.EnterpriseData.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EnterpriseDataService {
    private static Logger log = LoggerFactory.getLogger(EnterpriseDataService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private EnterpriseDataRepository enterpriseDataRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private DayUseUserNumRepository dayUseUserNumRepository;

    public String work() throws Exception {

        //成员使用统计
        count();

        return "SUCCESS";
    }

    public void count(){

        try{
            log.info("EnterpriseDataService 成员使用统计  start");

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String localDate = formatter.format(date);
            localDate="'"+localDate+"'";

            String deleteSQL =" delete from saas_enterprise_user_statistics where  DATE_FORMAT(stat_time, '%Y-%m-%d') =  " +localDate;
            String deleteSQL2 ="delete from day_use_user_num where  DATE_FORMAT(stat_date, '%Y-%m-%d') = "+localDate;
            //删除当前统计时间记录
            jdbcTemplate.execute(deleteSQL);
            jdbcTemplate.execute(deleteSQL2);

            //1、定时统计企业员工数据【当前企业人数、激活统计人数、未激活人数、离职人数】

            //查询所有企业
            List<DepartmentHierarchy> departmentHierarchyList= departmentHierarchyRepository.findAll();
            //结果值集合
            List<UserStatistics> userStatisticsList= new ArrayList<>();

            List<DayUseUserNum> dayUseUserNumList= new ArrayList<>();

            for(DepartmentHierarchy hierarchy : departmentHierarchyList){

                String sql = "SELECT id FROM ( SELECT t1.id,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM ( SELECT id,parent_id FROM `saas_department` t ORDER BY parent_id, id ) t1,(SELECT @pids := ?) t2 ) t3 WHERE ischild != 0 \n";
                List<Long> ids = jdbcTemplate.queryForList(sql, new Object[] { hierarchy.getOrgId() },Long.class);
                ids.add(hierarchy.getOrgId());

                // 非离职状态集合
                List<Integer> status = new ArrayList<>();
                status.add( 0);
                status.add( 1);
                StringBuffer depId = new StringBuffer();
                for (Long id : ids) {
                    depId.append(id).append(",");
                }
                String depIds = depId.substring(0, depId.lastIndexOf(","));

                // 企业总人数
                String count = "SELECT u.status FROM `saas_user_department_ref` d INNER JOIN  `saas_user` u ON d.user_id=u.id  WHERE d.`dep_id` IN ("
                        + depIds + ") ";
                List<Integer> companyPeopleCount = jdbcTemplate.queryForList(count, Integer.class);
                //status : 0未激活 1已激活 2已离职
                List<Integer> companyPeopleNumber = companyPeopleCount.stream().filter((Integer u) -> status.contains(u)).collect(Collectors.toList());
                List<Integer> activateNumber = companyPeopleCount.stream().filter((Integer u) -> u.equals(1)).collect(Collectors.toList());
                List<Integer> disableNumber = companyPeopleCount.stream().filter((Integer u) -> u.equals(0)).collect(Collectors.toList());
                List<Integer> dimissionNumber = companyPeopleCount.stream().filter((Integer u) -> u.equals(2)).collect(Collectors.toList());

                UserStatistics userStatistics =new UserStatistics();
                userStatistics.setOrgId(hierarchy.getOrgId());
                userStatistics.setTotalNumber(companyPeopleNumber.size());
                userStatistics.setActivateNumber(activateNumber.size());
                userStatistics.setDisableNumber(disableNumber.size());
                userStatistics.setDimissionNumber(dimissionNumber.size());
                userStatistics.setStatTime(date);

                userStatisticsList.add(userStatistics);

                //企业使用人数，每天的数据
                String countSql = "SELECT COUNT(distinct user_id) FROM saas_enterprise_operation WHERE " +
                        " org_id=? AND DATE_FORMAT(operation_time, '%Y-%m-%d') = "+localDate;
                Integer useUserCount = jdbcTemplate.queryForObject(countSql,
                        new Object[] { hierarchy.getOrgId() }, Integer.class);

                DayUseUserNum dayUseUserNum = new DayUseUserNum();
                dayUseUserNum.setDepId(hierarchy.getOrgId());
                dayUseUserNum.setStatDate(date);
                dayUseUserNum.setUserNum(useUserCount);
                dayUseUserNumList.add(dayUseUserNum);

            }

            enterpriseDataRepository.saveAll(userStatisticsList);
            dayUseUserNumRepository.saveAll(dayUseUserNumList);

            log.info("EnterpriseDataService 成员使用统计  end");
        }catch (Exception e){

            log.error("成员使用统计异常  " + e.getMessage(),e);
        }

    }

}
